/*!
 * Golazo GeoNotes
 * Copyright (C) 2009 Nakajiman Software Inc.
 * http://nakajiman.lrlab.to/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License 
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

/*!
 * jQuery remove self link plugin 1.0.0
 * http://developmentor.lrlab.to/
 *
 * Copyright(C) 2008 LEARNING RESOURCE LAB
 * http://friendfeed.com/nakajiman
 * http://hp.submit.ne.jp/d/16750/
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
$.fn.removeSelfLink = function() {
  var self = this;
  var href = location.href.split('#');
  return self
    .find('a')
    .each(function() {
      if (href[0] == this.href)
        $(this).before(this.childNodes).remove();
      })
    .end();
};

/**
 * Golazo
 */
if (typeof(Golazo) == 'undefined')
  Golazo = {};

if (location.hostname == 'golazo.aptanacloud.com') {

// Golazo.GOOGLE
Golazo.GOOGLE_APIKEY = 'ABQIAAAA38HauxeH3H_8yAPzIR8sIhRn5RHPmqla7RpY3ME98jE5TJ-ydBQSmd_gY1HRdB_ZJ6q2amqrGiik2g';
Golazo.GOOGLE_FCID = '15133558828380891487';

} else {

// Golazo.GOOGLE
Golazo.GOOGLE_APIKEY = 'ABQIAAAA38HauxeH3H_8yAPzIR8sIhReknmRmLwi9naG74oCRbQ4vYMk4RT6vS8FlByNtSAF1lxrxOcMnLqk6g';
Golazo.GOOGLE_FCID = '03107305587796150323';

}

// Golazo.GOOGLE
Golazo.GOOGLE_FCAUTH = 'fcauth' + Golazo.GOOGLE_FCID;
Golazo.GOOGLE_FCRPCURL = 'http://friendconnect.gmodules.com/ps/api';
Golazo.GOOGLE_FCSKIN = {
  'FONT_FAMILY': 'verdana,sans-serif',
  'BORDER_COLOR': '#ffffff',
  'ENDCAP_BG_COLOR': '#ffffff',
  'ENDCAP_TEXT_COLOR': '#000000',
  'ENDCAP_LINK_COLOR': '#0000cc',
  'ALTERNATE_BG_COLOR': '#ffffff',
  'CONTENT_BG_COLOR': '#ffffff',
  'CONTENT_LINK_COLOR': '#0000cc',
  'CONTENT_TEXT_COLOR': '#333333',
  'CONTENT_SECONDARY_LINK_COLOR': '#0000cc',
  'CONTENT_SECONDARY_TEXT_COLOR': '#333333',
  'CONTENT_HEADLINE_COLOR': '#333333'
};

// Golazo.YAHOO
Golazo.YAHOO_APPID = 'vF78APHV34Eim0hLiVfFf2jcs4D8cgIYBjjLHSavfHW7LsVJAU7zKEZgQVkJqSSGnBlxedpU8J8pYw--';

// Golazo.REGEX -- http://www.din.or.jp/~ohzaki/perl.htm#Mail
Golazo.REGEX_EMAIL = /^(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*")(?:\.(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|"[^\\\x80-\xff\n\015"]*(?:\\[^\x80-\xff][^\\\x80-\xff\n\015"]*)*"))*@(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\])(?:\.(?:[^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff]+(?![^(\040)<>@,;:".\\\[\]\000-\037\x80-\xff])|\[(?:[^\\\x80-\xff\n\015\[\]]|\\[^\x80-\xff])*\]))*$/;

// Golazo.checkPresence
Golazo.checkPresence = function(val) {
  return !val.match(/^[\u3000\s]*$/);
}

// Golazo.checkDigit
Golazo.checkDigit = function(val) {
  return val.match(/^[+-]?[0-9]+$/);
}

// Golazo.checkEmail
Golazo.checkEmail = function(val) {
  return val.length <= 255 && val.match(Golazo.REGEX_EMAIL);
};

/**
 * jQuery.fn.staticmaps
 */ 
$.fn.staticmaps = function(lat, lng, alt, width, height) {

  return this.each(function() {

    this.alt = lat+','+lng;
    this.src = 'http://maps.google.com/staticmap?' + $.param({  
      key: Golazo.GOOGLE_APIKEY,
      center: lat+','+lng,
      zoom: alt,
      size: [ width || this.width, height || this.height ].join('x'),
      markers: lat+','+lng
    });
  
  });

};

/**
 * jQuery.fn.me
 */
$.fn.me = function(me) {

  $('.me.fcid', this).text(me.fcid);
  $('.me.nickname', this).text(me.nickname);
  $('.me.aboutMe', this).text(me.aboutMe);

  var canvasUrl = '/canvas.html?' + $.param({
    profileId: me.fcid, canvas: 1
  });

  $('a.me.canvasUrl', this)
    .attr('href', canvasUrl)
	.each(function() {
	  if (this.title == '')
	    this.title = me.nickname;
	});

  $('a.me.profileUrl', this)
	.attr('href', '/users/'+me.fcid+'.html')
	.each(function() {
	  if (this.title == '')
	    this.title = me.nickname;
	});

  $('img.me.thumbnailUrl', this)
	.attr('src', me.thumbnailUrl)
	.each(function() {
	  if (this.alt == '')
	    this.alt = me.nickname;
	});
  
  return this;

};

/**
 * jQuery.fn.you
 */
$.fn.you = function(you) {

  $('.you.fcid', this).text(you.fcid);
  $('.you.nickname', this).text(you.nickname);
  $('.you.aboutMe', this).text(you.aboutMe);

  var canvasUrl = '/canvas.html?' + $.param({
    profileId: you.fcid, canvas: 1
  });
  
  $('a.you.canvasUrl', this)
    .attr('href', canvasUrl)
	.each(function() {
	  if (this.title == '')
	    this.title = you.nickname;
	});

  $('a.you.profileUrl', this)
	.attr('href', '/users/'+you.fcid+'.html')
	.each(function() {
	  if (this.title == '')
	    this.title = you.nickname;
	});

  $('img.you.thumbnailUrl', this)
	.attr('src', you.thumbnailUrl)
	.each(function() {
	  if (this.alt == '')
	    this.alt = you.nickname;
	});

  return this;

};

/**
 * jQuery.fn.note
 */
$.fn.note = function(note) {

  $('div.description', this)
    .append($('<span/>').text(note.description));

  var html = $('div.html', this);
  
  $.each(note.text.split(/\r?\n/), function(i, line) {
	$('<span/>').text(line).appendTo(html);
	$('<br/>').appendTo(html)
  });

  var days = Math.floor(note.since / 86400000);
  var hours = Math.floor(note.since / 3600000);
  var minutes = Math.floor(note.since / 60000);
  var seconds = Math.round(note.since / 1000);

  $('.since', this).text(
    days ? days+' days ago' : (
	hours ? hours+' hours ago' : (
	minutes ? minutes+' minutes ago' : seconds+' seconds ago'
  )));

  $('a.mapUrl', this)
    .attr('href', 'http://maps.google.co.jp/maps?q='+note.latitude+','+note.longitude)
	.attr('target', '_blank');

  $('img.map', this)
    .staticmaps(note.latitude, note.longitude, note.altitude, 120, 90);

  $('img.map.medium', this)
    .staticmaps(note.latitude, note.longitude, note.altitude);

  $('a.readUrl', this)
    .attr('href', '/notes/'+note.id+'.html');

  if (note.user.isMe)
    $('div.menubar span', this).show();

  return this.attr('id', 'note'+note.id).you(note.user);

};

/**
 * jQuery.fn.createNote
 */
$.fn.createNote = function() {
  
  return this.submit(function() {

    var form = this;
    var error = $('div.message', form).hide();

	if (!Golazo.checkPresence(form.text.value))
	  return false;

    var icon = $(':submit', this)
	if (icon.hasClass('indicatorr'))
	  return false;
	icon.addClass('indicatorr');

	createNote.async([
      function(notes) {
		icon.removeClass('indicatorr');
        if (notes.length == 0)
		  error.text('Sorry, could not detect geographic coordinate. Please give more text and try again.').show();
		else {
		  form.text.value = '';
		  $.each(notes.reverse(), function(i, note) {		
            $('#notes div.note:hidden').clone()
		      .note(note).deleteNote().prependTo('#notes').fadeIn(600*2);
          });
		}
      }, function(e) {
		icon.removeClass('indicatorr');
		error.text('Oops, there was a problem!').show();
	  }
    ], {
	  text: form.text.value
	});

    return false;
  
  });

};

/**
 * jQuery.fn.deleteNote
 */
$.fn.deleteNote = function() {

  return this.each(function(i, note) {
	
	$('a.deleteUrl', note).click(function() {
	  
	  if (!confirm('Sure you want to delete this note? There is NO undo!'))
	    return false;
      
	  var icon = $(this).parent();
	  if (icon.hasClass('indicatorr'))
		return false;
	  icon.removeClass().addClass('indicatorr');
	  
	  deleteNote.async([
		function() {
	      $(note).fadeOut(600*2, function() {
		    $(this).remove();
		  });
	    }, function(e) {
	      icon.removeClass().addClass('errorr');
	    }
	  ], note.id.replace(/[^0-9]/g, ''));
	  
	  return false;

    });
	
  });

};

/**
 * jQuery.fn.module
 */
$.fn.module = function(module) {

  var days = Math.floor(module.since / 86400000);
  var hours = Math.floor(module.since / 3600000);
  var minutes = Math.floor(module.since / 60000);
  var seconds = Math.round(module.since / 1000);

  $('.since', this).text(
    days ? days+' days ago' : (
	hours ? hours+' hours ago' : (
	minutes ? minutes+' minutes ago' : seconds+' seconds ago'
  )));

  if (module.user.isMe)
    $('div.menubar span', this).show();

  return this.attr('id', 'module'+module.id).you(module.user);

};

/**
 * jQuery.fn.createModule
 */
$.fn.createModule = function(noteId) {

  return this.each(function(i, gadget) {

	$('a.addUrl', gadget).click(function() {

	  var icon = $(this).parent();
	  if (icon.hasClass('indicatorr'))
		return false;
	  icon.removeClass().addClass('indicatorr');

	  createModule.async([
		function() {
	      icon.removeClass().addClass('checkr');
		  $(gadget).fadeOut(600*2, function() {
	        $(this).remove();
		    location.href = '/notes/'+noteId+'.html';
		  });
	    }, function(e) {
	      icon.removeClass().addClass('errorr');
	    }
	  ], noteId, gadget.id.replace(/[^0-9]/g, ''), {});

      return false;

    });
  
  });

};

/**
 * jQuery.fn.deleteModule
 */
$.fn.deleteModule = function() {

  return this.each(function(i, module) {
	
	$('a.deleteUrl', module).click(function() {
	  
	  if (!confirm('Sure you want to delete this gadget? There is NO undo!'))
	    return false;
      
	  var icon = $(this).parent();
	  if (icon.hasClass('indicatorr'))
		return false;
	  icon.removeClass().addClass('indicatorr');
	  
	  deleteModule.async([
		function() {
	      $(module).fadeOut(600*2, function() {
		    $(this).remove();
		  });
	    }, function(e) {
	      icon.removeClass().addClass('errorr');
	    }
	  ], module.id.replace(/[^0-9]/g, ''));
	  
	  return false;

    });
	
  });

};